


#include <stdlib.h>
#include <stdio.h>

#include <string.h>


typedef struct{
	char		*filename;
	int			address;
}event_;



event_ event;


int		rom_address_event(FILE*file,int romaddress,int address,int space){
	if(romaddress<0&&romaddress>-5)
	{
		return 0;
	}

	if(romaddress<0x08000000||romaddress>0x0A000000){
		printf("地址错误,位置在0x%08X\n",address);
		return 1;
	}
	romaddress -=	0x08000000;
	return out_event(file,romaddress,space);
}


int		out_event(FILE*file,int address,int space){
	int		buf;
	int		count;
	int		i;
	int		type;
	int		addr;

	printf("\n\n");
	printf("_%08X:\n",address);
	printf("%*s{\n",space,"");
	buf		=	0;
	addr	=	0;
	fseek(file,address,SEEK_SET);
	do{

		address	+=	2;
		fread(&buf,1,2,file);
		count	=	(buf>>4)&0xf;
		type	=	(buf>>8)&0xff;

		printf("%*s",space,"");

		printf("0x%04X ",buf);

		for(i=0;i<count-1;i++){
			address	+=	2;
			fread(&buf,1,2,file);
			printf("0x%04X ",buf);


			if(type==0xA){
				if(i==1){
					addr=buf;

				}
				else if(i==2){
					addr|=(buf<<0x10);
				}
			}
		}
		printf("\n");

		if(type==1){
			break;
		}

		if(type==0xA){
			if(rom_address_event(file,addr,address,space + 4)){
				return 1;
			}
			fseek(file,address,SEEK_SET);
		}

		if(type>0x55){
			return 1;
		}
	}while(1);
	printf("%*s}\n",space,"");
	return 0;
}



int		convert_(event_*e){
	FILE		*file;

	file	=	fopen(e->filename,"rb");
	if(!file){
		printf("打开文件失败\n");
		return -1;
	}

	out_event(file,e->address,0);

	fclose(file);

	return 0;
}



int		main(int c,char**v){
	memset(&event,0,sizeof(event));
	if(c<3){
		printf("参数错误\n");
		return -1;
	}

	event.filename	=	v[1];
	if(!sscanf(v[2],"%X",&event.address)){
		printf("参数2转换失败\n");
		return -1;
	}

	return convert_(&event);
}
